package in.muton.edushare.pages.cp.backup.restore;

import in.muton.edushare.pages.EduShareBasePage;
import in.muton.edushare.pages.common.EdusharePanel;
import in.muton.edushare.wicket.models.CayenneModel;

import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.markup.html.IHeaderContributor;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;

import com.edushare.common.backup.SystemRestoreUtils;
import com.edushare.common.util.DateTimeUtil;
import com.edushare.common.util.SystemUtils;
import com.edushare.common.vo.SystemBackup;

public class StartRestorePanel extends EdusharePanel implements IHeaderContributor {

	private static final long serialVersionUID = -7794862025133405567L;
	private CayenneModel<SystemBackup> bkpModel;
	private Log log = LogFactory.getLog(StartRestorePanel.class);
	Form<Void> form;
	
	public StartRestorePanel(String id, CayenneModel<SystemBackup> bkpModel, EduShareBasePage page, RestorePanel restorePanel) {
		super(id,bkpModel, page);
		this.bkpModel = bkpModel;
		add(new Label("ttl", bkpModel.getObject().getBackupTitle()));
		add(new Label("tstamp", DateTimeUtil.formatTimestamp(bkpModel.getObject().getCreationTimestamp())));
		add(form = new Form<Void>("form"){

			private static final long serialVersionUID = 3051495207816519895L;

			@Override
			protected void onSubmit() {
				startBackup();
			}
		});
		form.setOutputMarkupId(true);
	}

	private void startBackup() {

		try {
			SystemRestoreUtils.createRestoreScript(bkpModel.getObject());
			String shellFile = SystemUtils.getAbsolutePathFromRelative(bkpModel.getObject().getDirectoryPath())+"/"+SystemBackup.RESTORE_SCRIPT_FILE_NAME;
			Process p = Runtime.getRuntime().exec("chmod a+x "+ shellFile);
			
			//wait till authorization is alloted
			p.waitFor();
			String cmd = "/bin/sh " + shellFile;
					/*"/bin/sh -c \"" + shellFile
								  + " > " 
								  + SystemUtils.getAbsolutePathFromRelative(bkpModel.getObject().getDirectoryPath())+"/log.txt"
								  + "\"";*/
			Runtime.getRuntime().exec(cmd);
		} catch (FileNotFoundException e) {
			log.error("Error while starting restore process. Backup Id: [" + bkpModel.getObject().getSystemBackupId()+"]", e);
		} catch (IOException e) {
			log.error("Error while starting restore process. Backup Id: [" + bkpModel.getObject().getSystemBackupId()+"]", e);
		} catch (InterruptedException e) {
			log.error("Error while starting restore process. Backup Id: [" + bkpModel.getObject().getSystemBackupId()+"]", e);
		}
		
	
	}

	public void renderHead(IHeaderResponse resp) {
		resp.renderOnDomReadyJavascript("" +
				"$('#alertDiv').dialog({"+
			    "autoOpen: false,"+
			    "width: 600,"+
			    "modal: true,"+
			    "buttons: {"+
			        "\"Ok\": function() {"+ 
			        "$(this).dialog(\"close\");"+
			        "$('#"+form.getMarkupId()+"').submit();"+
			         "return true; "+
			        "}, "+
			        "\"Cancel\": function() {"+ 
				    "$(this).dialog(\"close\");"+ 
			            "return false; "+
			        "} "+
			    "}"+
			"});"+
			"$('#startRestore').click(function(){$('#alertDiv').dialog('open');return false;});"+
				"");
	}

}
